package org.jeecg.modules.demo.util;


import com.thoughtworks.xstream.XStream;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import java.io.Reader;
import java.io.StringReader;
 
public class XmlBuilder {
 
    /**
     * JAXB将XML转为指定的POJO
     *
     * @param clazz
     * @param xml
     * @return
     */
    public static Object JAXB_XmlToBean(Class<?> clazz, String xml) {
        try {
            Object xmlObject;
            Reader reader;
            JAXBContext context = JAXBContext.newInstance(clazz);
            // XML 转为对象的接口
            Unmarshaller unmarshaller = context.createUnmarshaller();
            reader = new StringReader(xml);
            //以文件流的方式传入这个string
            xmlObject = unmarshaller.unmarshal(reader);
            reader.close();
            return xmlObject;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
 
    /**
     * XStream将XML转为指定的POJO
     *
     * @param clazz
     * @param xml
     * @return
     */
    public static Object XStream_ToBean(Class<?> clazz, String xml) {
        Object xmlObject;
        XStream xstream = new XStream();
        xstream.processAnnotations(clazz);
        xstream.autodetectAnnotations(true);
        xmlObject = xstream.fromXML(xml);
        return xmlObject;
    }
}